package com.xudow.app.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.activeshare.edu.ucenter.models.base.Activities;
import com.xudow.app.Config;
import com.xudow.app.R;
import com.xudow.app.ui.adapter.ActivityMessageAdapter;
import com.xudow.app.ui.support.RecyclerViewScrollLocationListener;
import com.xudow.app.ui.support.XLinearLayoutManager;
import com.xudow.app.ui.task.ActivitiesTask;
import com.xudow.app.util.Maps;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * 活动消息Fragment
 *
 * @author lukecheng
 */
public class ActivitiesMessageFragment extends BaseFragment
        implements ActivityMessageAdapter.OnRecyclerViewListener {

    private static final int COURSES_FIRST = 0; //第一次获取
    private static final int COURSES_PREV = 1;  //底部加载更多

    private int refreshStatus = COURSES_FIRST;

    private List<Activities> activities;
    private ActivityMessageAdapter activityMessageAdapter;

    private RecyclerView orderRecyclerView;
    private ProgressBar progressBar;
    private LinearLayout contentView;
    private RelativeLayout emptyView;

    private ActivitiesTask activitiesTask;

    private int page = 1;  //当前页数

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_activity_message_list, container, false);

        emptyView = (RelativeLayout) v.findViewById(R.id.enroll_require_prompt);

        orderRecyclerView = (RecyclerView) v.findViewById(R.id.order_list);
        orderRecyclerView.setHasFixedSize(true);

        XLinearLayoutManager layoutManager = new XLinearLayoutManager(getActivity());
        layoutManager.setOnRecyclerViewScrollLocationListener(orderRecyclerView,
                new RecyclerViewScrollLocationListener() {
                    @Override
                    public void onTopWhenScrollIdle(RecyclerView recyclerView) {
                    }

                    @Override
                    public void onBottomWhenScrollIdle(RecyclerView recyclerView) {
                        refreshStatus = COURSES_PREV;

                        //设置页数
                        page++;
                        loadMessages();
                    }
                });
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        orderRecyclerView.setLayoutManager(layoutManager);

        progressBar = (ProgressBar) v.findViewById(R.id.progressbar);
        contentView = (LinearLayout) v.findViewById(R.id.content);

        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        activities = new ArrayList<Activities>();

        activityMessageAdapter = new ActivityMessageAdapter(activities);
        activityMessageAdapter.setOnRecyclerViewListener(this);
        orderRecyclerView.setAdapter(activityMessageAdapter);

        loadMessages();
    }

    @Override
    public void onItemClick(int position) {
        Activities activity = activities.get(position);

        Intent intent = new Intent(getActivity(), ActivityViewActivity.class);
        intent.putExtra("activityId", activity.getId());
        intent.putExtra("activityPageUrl", activity.getActivityPageUrl());
        intent.putExtra("activityTitle", activity.getTitle());
        startActivity(intent);
    }

    @Override
    public boolean onItemLongClick(int position) {
        return false;
    }

    /**
     * 获取Message Handler
     */
    private Handler messageListTaskHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == ActivitiesTask.SUCCESS) {
                onActivityListSuccess(msg.getData());
            } else {
                if (page > 1) {
                    page--;
                }
            }
        }
    };

    private void onActivityListSuccess(Bundle data) {
        Activities[] activitiesArr = (Activities[]) data.getSerializable("activities");

        if (null == activitiesArr || activitiesArr.length <= 0) {
            if (page > 1) {
                page--;
            }

            progressBar.setVisibility(View.GONE);

            if (activities.size() <= 0) {
                contentView.setVisibility(View.GONE);
                emptyView.setVisibility(View.VISIBLE);
            }

            return;
        }

        activities.addAll(Arrays.asList(activitiesArr));

        if (activities.size() <= 0) {
            contentView.setVisibility(View.GONE);
            emptyView.setVisibility(View.VISIBLE);
        }

        progressBar.setVisibility(View.GONE);
        emptyView.setVisibility(View.GONE);
        contentView.setVisibility(View.VISIBLE);

        activityMessageAdapter.notifyDataSetChanged();
    }

    private void loadMessages() {
        HashMap<String, String> params = Maps.newHashMap();
        params.put(Config.PAGINATION_PARAM_NAME, "" + this.page);

        activitiesTask = new ActivitiesTask(getActivity(), messageListTaskHandler);
        activitiesTask.execute(params);
    }

    @Override
    public void onDestroy() {
        if (null != activitiesTask && !activitiesTask.isCancelled()) {
            activitiesTask.cancel(true);
            activitiesTask = null;
        }

        super.onDestroy();
    }
}